package com.yuxin.tongyi.lsll.main;

import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.yuxin.tongyi.lsll.R;
import com.yuxin.tongyi.lsll.common.Constants;
import com.yuxin.tongyi.lsll.common.TongyiTeaApplication;
import com.yuxin.tongyi.lsll.pojo.LoginInfo;
import com.yuxin.tongyi.lsll.pojo.TeacherInfo;
import com.yuxin.tongyi.lsll.pojo.VersionInfo;
import com.yuxin.tongyi.lsll.service.NetworkListenerService;
import com.yuxin.tongyi.lsll.service.VersionService;
import com.yuxin.tongyi.lsll.thread.SaveClassDataThread;
import com.yuxin.tongyi.lsll.thread.SaveEventDataThread;
import com.yuxin.tongyi.lsll.util.FileTool;
import com.yuxin.tongyi.lsll.util.HttpRequestUtil;
import com.yuxin.tongyi.lsll.util.PubUtil;

public class LoginActivity extends Activity {
	private final static String TAG = "LoginActivity";
	
	private EditText et_LoginName, et_Password;
	private CheckBox cb_remember, chb_autologin;
	private Button btnOk, btnQuit;
	
	private HttpRequestUtil reqeustUtil;
	private LoginHandler loginHandler;
	private VerThread verThread;//检查版本线程
	private LoginThread loginThread; //登陆线程
	
	private PowerManager powerManager;
	private WakeLock wakeLock;
	 
    //返回的安装包url
	private String apkUrl ;
	

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);
		
//		this.powerManager = (PowerManager)this.getSystemService(Context.POWER_SERVICE);         
//		this.wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
//		wakeLock.acquire();
		initActivity();
		
		reqeustUtil = new HttpRequestUtil();
		loginHandler = new LoginHandler();
		
		loginThread = new LoginThread();
		//重新登陆
		Bundle data = getIntent().getExtras();
		if(data != null){
			if(data.getInt(Constants.LOGIN_KEY_FLAG) == Constants.LOGIN_VALUE_RE){
				return;
			}
		}
		PubUtil.showProgressDialog(LoginActivity.this, "提示", "检查版本信息");
		
		verThread = new VerThread();
		new Thread(verThread).start();
		
		Intent intent = new Intent();
		intent.setClass(LoginActivity.this,NetworkListenerService.class);
		startService(intent); //启动监控网络状态的service
	}
	
	public void initActivity(){
		btnOk = (Button) findViewById(R.id.login_btnEnter);
		btnOk.setOnClickListener(loginbtnClick);
		btnQuit = (Button) findViewById(R.id.login_btnExit);
		btnQuit.setOnClickListener(quitbtnClick);
		
		et_LoginName = (EditText) findViewById(R.id.login_edtUsername);
		et_Password = (EditText) findViewById(R.id.login_edtPassword);
		cb_remember = (CheckBox) findViewById(R.id.login_chbSavePassword);
		chb_autologin = (CheckBox) findViewById(R.id.login_chbAutoLogin);
		chb_autologin.setOnClickListener(new AutoLoginCheckedListener());
		//读取登陆设置
		cb_remember.setChecked(PubUtil.getConfigValue(LoginActivity.this, Constants.CFG_REMEMBER, false));
		chb_autologin.setChecked(PubUtil.getConfigValue(LoginActivity.this, Constants.CFG_AUTOLOGIN, false));
		if(cb_remember.isChecked()){
			et_LoginName.setText(PubUtil.getConfigValue(LoginActivity.this, Constants.CFG_LOGINNAME, ""));
			et_Password.setText(PubUtil.getConfigValue(LoginActivity.this, Constants.CFG_LOGINPASSWORD, ""));
		}
	}
	
	/**
	 *单击选择自动登录按钮时，同时勾选记录密码 
	 *
	 */
	class AutoLoginCheckedListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			//当选中自动登录时，勾选记住密码
			if(chb_autologin.isChecked()){
				cb_remember.setChecked(true);
			}
		}
		
	}
	
	class LoginHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			switch (msg.what) {
			case Constants.TH_LOGIN:
				//保存登陆设置
				if (cb_remember.isChecked()) {
					PubUtil.setConfigValue(LoginActivity.this, Constants.CFG_LOGINNAME, et_LoginName.getText().toString());
					PubUtil.setConfigValue(LoginActivity.this, Constants.CFG_LOGINPASSWORD, et_Password.getText().toString());
				} else {
					//判断是否自动登录
					if(chb_autologin.isChecked()){
						cb_remember.setChecked(true);
					}
				}
				PubUtil.setConfigValue(LoginActivity.this, Constants.CFG_AUTOLOGIN, chb_autologin.isChecked());
				PubUtil.setConfigValue(LoginActivity.this, Constants.CFG_REMEMBER, cb_remember.isChecked());
				//清除基础数据标识
				PubUtil.setConfigValue(LoginActivity.this, Constants.CFG_CLASS_STATE, 0);
				PubUtil.setConfigValue(LoginActivity.this, Constants.CFG_EVENT_STATE, 0);
				PubUtil.setConfigValue(LoginActivity.this, Constants.CFG_STUDENT_STATE, 0);
				
				Bundle lbudle = msg.getData();
				TeacherInfo tinfo = (TeacherInfo) lbudle.getSerializable("TeacherInfo");
				LoginInfo loginInfo = new LoginInfo();
				loginInfo.setLoginName(et_LoginName.getText().toString());
				loginInfo.setPassword(et_Password.getText().toString());
				HashMap<String, Object> map;
				try {
					map = TongyiTeaApplication.getMap();
					map.put(Constants.GLOBAL_LOGININFO, loginInfo);
					map.put(Constants.GLOBAL_TEACHERINFO, tinfo);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				//获取班级信息线程
				new Thread(new SaveClassDataThread(LoginActivity.this, loginInfo)).start();
				//获取领域信息线程
				new Thread(new SaveEventDataThread(LoginActivity.this, loginInfo)).start();
				
				try {
					Thread.sleep(3000);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				PubUtil.closeProgressDialog();
				
				//当不请求服务器时也跳转到主界面，用户加载缓存数据
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, MainActivity.class);
				startActivity(intent);
				LoginActivity.this.finish();
				break;
			case Constants.TH_LOGIN_ERROR:
				PubUtil.closeProgressDialog();
				PubUtil.showDialog(LoginActivity.this, "提示", Constants.MSG_LOGIN_ERROR, null, false);
				//PubUtil.showToast(LoginActivity.this, Constants.MSG_LOGIN_ERROR);
				break;
			case Constants.TH_VERSION:
				Bundle budle = msg.getData();
				VersionInfo info = (VersionInfo) budle.getSerializable("versionInfo");
				PubUtil.closeProgressDialog();
				showNoticeDialog(info);
				break;
			case Constants.TH_SERVER_OFF:
				PubUtil.closeProgressDialog();
				PubUtil.showToast(LoginActivity.this, Constants.MSG_SERVER_OFF);
				break;
			case Constants.TH_DATA_ERROR:
				PubUtil.closeProgressDialog();
				PubUtil.showToast(LoginActivity.this, Constants.MSG_DATA_ERROR);
			    break;
			case Constants.TH_NODATA:
				PubUtil.closeProgressDialog();
				PubUtil.showToast(LoginActivity.this, Constants.MSG_NODATA);
			    break;
			}
		}
	}

	/**
	 * 版本线程
	 *
	 */
	class VerThread implements Runnable {
		public void run() {
			try {
				boolean flag = reqeustUtil.validateVersion();
				String status = reqeustUtil.getStatus();
				Message msg = loginHandler.obtainMessage();
				if (flag) {// 服务器响应
					if (status != null && !"".equals(status)) {//请求成功
						List<Object> objects = reqeustUtil.getObjList();
						if (objects != null && objects.size() > 0) {//服务器响应数据
							Bundle bundle = new Bundle();
							
							Object obj = objects.get(0);
							if (obj instanceof VersionInfo) {
								VersionInfo info = (VersionInfo) objects.get(0);
								bundle.putSerializable("versionInfo", info);
							}
							msg.what = Constants.TH_VERSION;
							msg.setData(bundle);
						} else {//暂无数据
							msg.what = Constants.TH_NODATA;
						}
					} else { //数据异常
						msg.what = Constants.TH_DATA_ERROR;
					}
				} else { // 访问服务器失败
					msg.what =  Constants.TH_SERVER_OFF;
				}
				loginHandler.sendMessage(msg);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	};

	class LoginThread implements Runnable{

		public void run() {
			boolean flag = reqeustUtil.LoginRequest(
					et_LoginName.getText().toString(),
					et_Password.getText().toString());
			String status = reqeustUtil.getStatus();
			Message msg = loginHandler.obtainMessage();
			if (flag) {// 服务器响应
				if (status != null && !"".equals(status)) {//请求成功
					if(status.equals("0")){
						List<Object> objects = reqeustUtil.getObjList();
						if (objects != null && objects.size() > 0) {//服务器响应数据
							Bundle bundle = new Bundle();
							TeacherInfo info = (TeacherInfo) objects.get(0);
							bundle.putSerializable("TeacherInfo", info);
							msg.what = Constants.TH_LOGIN;
							msg.setData(bundle);
						}	
					}else if("2".equals(status)) {//用户名或密码错误
						msg.what = Constants.TH_LOGIN_ERROR;
					}
				} else { //数据异常
					msg.what = Constants.TH_DATA_ERROR;
				}
			} else { // 访问服务器失败
				msg.what =  Constants.TH_SERVER_OFF;
			}
			loginHandler.sendMessage(msg);
		};
	}
	
	private OnClickListener loginbtnClick = new OnClickListener() {

		public void onClick(View v) {
			try {
				if (et_LoginName.getText() != null
						&& !("").equals(et_LoginName.getText())
						&& et_LoginName.getText().length() > 0
						&& et_Password.getText() != null
						&& !("").equals(et_Password.getText())
						&& et_Password.getText().length() > 0) {
						
					PubUtil.showProgressDialog(LoginActivity.this, "登录中", "请稍后...");
					new Thread(new LoginThread()).start();
				} else {
					Toast.makeText(LoginActivity.this, "请输入用户名和密码！", Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(LoginActivity.this, "获取数据出错！", Toast.LENGTH_SHORT).show();
			}

		}
	};

	private OnClickListener quitbtnClick = new OnClickListener() {

		public void onClick(View v) {
			PubUtil.showDialog(LoginActivity.this, "提示", "是否退出程序？", 
					new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								System.exit(0);
						}
			}, true);
		}
	};

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			PubUtil.showDialog(LoginActivity.this, "提示", "是否退出程序？", 
					new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								System.exit(0);
						}
			}, true);
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 检查更新
	 */
	private void showNoticeDialog(VersionInfo info){
		AlertDialog.Builder builder = new Builder(this);
		Dialog noticeDialog;
		//检测是否有版本更新
		if(info != null) {
			int currentVersion = getAppVersionCode(this);
			int newVersion = Integer.parseInt(info.getVersionCode());
			if(newVersion>0) {
				if(currentVersion < newVersion) {
					apkUrl = info.getUrl();
	//				size = Double.valueOf(info.getSize());
					builder.setTitle("软件版本更新");
					builder.setMessage(Constants.MSG_VERSION_NEW);
					builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {			
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							startVersionService();			
						}
					});
					builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {			
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();				
						}
					});
					noticeDialog = builder.create();
					noticeDialog.show();
				}else{
					if(chb_autologin.isChecked()){
						btnOk.performClick();
					}
				}
			}
		}
	}
	
	/**
	 * 返回当前应用程序版本名
	 */
	public static double getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager manage = context.getPackageManager();
			PackageInfo info = manage.getPackageInfo(context.getPackageName(), 0);
			versionName = info.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return 1.0;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Double.valueOf(versionName);
	}
	
	/**
	 * 返回当前应用程序版本号
	 */
	public static int getAppVersionCode(Context context) {
		int versionCode = 0;
		try {
			// ---get the package info---
			PackageManager manage = context.getPackageManager();
			PackageInfo info = manage.getPackageInfo(context.getPackageName(), 0);
			versionCode = info.versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionCode;
	}
	
	/**
	 * 启动检查版本service
	 */
	private void startVersionService() {
		Intent intent = new Intent();
		intent.putExtra("apkUrl",apkUrl);
		String savePath = "";
		if(FileTool.sdCardExist()) {//存在
			//savePath = this.getExternalCacheDir().toString();
			savePath = Environment.getExternalStorageDirectory().toString();
		}else {//sdcard不存在
			savePath = this.getCacheDir().toString();
		}
		if(null==apkUrl||"".equals(apkUrl)||null==savePath||"".equals(savePath)) {
			return;
		}
		intent.putExtra("savePath",savePath);
		intent.setClass(LoginActivity.this,VersionService.class);
		startService(intent); //启动service
	}
	
}
